﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using Newtonsoft.Json;
using System.Web;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using HtmlAgilityPack;
namespace CheCeShi
{
    public class Program
    {
        public static void Main(string[] args)
        {

            // Console.WriteLine(GetPinPaiInfo());

            //foreach (ChePinPai item in GetPinPaiInfo())
            //{
            //    Console.WriteLine(item.PinPaiId);
            //}
            //var dic = GetPinPaiId();
            //string json = (new JavaScriptSerializer()).Serialize(dic);
            //Console.WriteLine(json);
            //foreach (var item in dic)
            //{
            //    Console.WriteLine("id:{0},name:{1}",item.Key, item.Value);
            //}
            //  GetCarSeries();
            //  Console.WriteLine(GetCarSeries("1"));
            // Console.WriteLine(GetCarSeries("1"));
            //  Console.WriteLine(GetCarPrice());
            //ChePrice cheprice = GetCarPrice();
            //foreach (var item in cheprice.price)
            //{
            //    Console.WriteLine(item.ToString());
            //}
            //Console.WriteLine(GetCity());
             Console.WriteLine(GetCheHomePinPai());
            //Console.WriteLine(  GetCheHomeSeries("33"));
            // Console.WriteLine(  CarModel("3170"));
            //  Console.WriteLine(GetCarModel("5"));
            // GetPrice();
            // Console.WriteLine(GetProvinces());
            #region 获取车系
            //一级菜单请求链接：https://ssl-meta.che300.com/meta/series/series_brand1.json?v=159
            //二级菜单请求链接：https://ssl-meta.che300.com/meta/model/model_series5.json?v=159
            //for (int i = 1; i < 700; i++)
            //{
            //    var url = "https://ssl-meta.che300.com/meta/series/series_brand" + i + ".json?v=159";
            //    BaseCrawler crawler = new BaseCrawler();
            //    crawler.OnStart += (s, e) =>
            //    {
            //        Console.WriteLine("地址:------------" + e.Uri.ToString());
            //    };
            //    crawler.OnError += (s, e) =>
            //    {
            //        Console.WriteLine("错误:------------" + e.Exception.Message);
            //    };
            //    crawler.OnCompleted += (s, e) =>
            //    {
            //        JArray Jstr = (JArray)JsonConvert.DeserializeObject(e.PageSource);
            //        for (int j = 0; j < Jstr.Count; j++)
            //        {
            //            string id = Jstr[j]["series_id"].ToString();//车系id
            //            string name = Jstr[j]["series_name"].ToString();//车系名称
            //            Console.WriteLine(name);

            //        }
            //        // Console.WriteLine(e.PageSource);
            //    };
            //    crawler.Start(new Uri(url)).Wait();

            //}
            #endregion

        }
        #region 车300数据获取
        #region 获取汽车品牌信息
        //  public static string PinPaiInfo;
        //  public static   
        public static List<ChePinPai> GetPinPaiInfo()
        {
            //获取汽车品牌
            ArrayList PinPaiList = new ArrayList();
            var CheUrl = "https://www.che300.com/";
            BaseCrawler baseCrawler = new BaseCrawler();

            baseCrawler.OnCompleted += (s, e) =>
            {
                HtmlWeb htmlWeb = new HtmlWeb();
                HtmlDocument document = htmlWeb.Load(e.Uri);
                HtmlNodeCollection collection = document.DocumentNode.SelectNodes("//p[@class='pinpailist list_1']");
                if (collection != null)
                {
                    foreach (var item in collection)
                    {
                        Dictionary<string, string> dictionary = new Dictionary<string, string>();
                        string PinPaiID = item.Attributes["id"].Value;//品牌Id
                        string PinPaiName = item.InnerText;//品牌名称
                        dictionary.Add("PinPaiId", PinPaiID);
                        dictionary.Add("PinPaiName", PinPaiName);
                        PinPaiList.Add(dictionary);
                        // Console.WriteLine(PinPaiID);
                    }

                }
            };

            baseCrawler.Start(new Uri(CheUrl)).Wait();
            // string json = (new JavaScriptSerializer()).Serialize(dictionary);
            string jstr = JsonConvert.SerializeObject(PinPaiList);
             List<ChePinPai>   pinPai = JsonConvert.DeserializeObject<List<ChePinPai>>(jstr);
            return pinPai;
        }
        #endregion
        #region 获取车系信息
        public static string CarSeriesInfo;
        /// <summary>
        /// 获取车系信息
        /// </summary>
        /// <param name="PinPaiId">品牌Id</param>
        /// <returns>返回车系Json字符串</returns>
        public static string GetCarSeries(string PinPaiId)
        {
            //获取汽车品牌id  利用id拼接链接地址        
            //获取车系的请求链接：https://ssl-meta.che300.com/meta/series/series_brand1.json?v=159   
            var CarSeriesUrl = "https://ssl-meta.che300.com/meta/series/series_brand" + PinPaiId + ".json";
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                CarSeriesInfo = e.PageSource;
            };
            baseCrawler.Start(new Uri(CarSeriesUrl)).Wait();
            return Regex.Unescape(CarSeriesInfo);
        }
        #endregion
        #region 获取车型信息
        /// <summary>
        /// 获取车型
        /// </summary>
        /// <param name="SeriesId">车系Id</param>
        /// <returns>返回车型json字符串</returns>
        public static string CarModelInfo;
        public static string GetCarModel(string SeriesId)
        {
            var CarSeriesUrl = "https://ssl-meta.che300.com/meta/model/model_series" + SeriesId + ".json";
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                CarModelInfo = e.PageSource;
            };
            baseCrawler.Start(new Uri(CarSeriesUrl)).Wait();
            return Regex.Unescape(CarModelInfo);
        }
        #endregion
        #region 获取汽车报价
        /// <summary>
        /// 获取汽车报价
        /// </summary>
        /// <param name="provId">省市Id</param>
        /// <param name="cityId">城市Id</param>
        /// <param name="brandId">品牌Id</param>
        /// <param name="seriesId">车系Id</param>
        /// <param name="modelId">车型Id</param>
        /// <param name="regDate">日期 格式xxxx-xx</param>
        /// <param name="mile"></param>
        /// <returns>获取报价json字符串</returns>
        /*  public static *//*ArrayList CarPriceS;*/
        public static ChePrice GetCarPrice()//string provId, string cityId, string brandId, string seriesId, string modelId, string regDate, string mile)
        {
            var dingjiaUrl = " https://dingjia.che300.com/app/EvalResult/getPreSaleRate?prov=12&city=12&brand=1&series=5&model=1134332&regDate=2017-1&mile=2";
            //var dingjiaUrl = "https://dingjia.che300.com/app/EvalResult/getPreSaleRate?prov=" + provId + "&city=" + cityId + "&brand=" + brandId + "&series=" + seriesId + "&model=" + modelId + "&regDate=" + regDate + "&mile" + mile;
            BaseCrawler baseCrawler = new BaseCrawler();
            ArrayList CarPriceS = new ArrayList();
            baseCrawler.OnCompleted += (s, e) =>
            {
                // CarPrice = e.PageSource;
                JObject jPrice = (JObject)JsonConvert.DeserializeObject(e.PageSource);
                string CarPrice = jPrice["success"].ToString();
                JArray jArray = (JArray)JsonConvert.DeserializeObject(CarPrice);
                foreach (var item in jArray)
                {
                    string price = item["price"].ToString();
                    CarPriceS.Add(price);
                }
            };
            baseCrawler.Start(new Uri(dingjiaUrl)).Wait();
            ChePrice chePrice = new ChePrice();
            chePrice.price = CarPriceS;

            return chePrice;
        }
        #endregion 
        #region 获取省市

        //https://dingjia.che300.com/api/lib/util/city/prov_with_city?callback=jQuery183014398943682875975_1524644792310&format=jsonp&_=1524644792535 省份Json
        public static string Prov;
        public static string GetProv()
        {
            var ProvUrl = "https://dingjia.che300.com/api/lib/util/city/prov_with_city";//包含省市
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                Prov = e.PageSource;
            };
            baseCrawler.Start(new Uri(ProvUrl)).Wait();
            return Regex.Unescape(Prov);
        }
        //https://ssl-meta.che300.com/location/all_city.json 城市Json
        //public static string City;
        //public static string GetCity()
        //{
        //    var CityUrl = "https://ssl-meta.che300.com/location/all_city.json";
        //    BaseCrawler baseCrawler = new BaseCrawler();
        //    baseCrawler.OnCompleted += (s, e) =>
        //    {
        //        City = e.PageSource;
        //    };
        //    baseCrawler.Start(new Uri(CityUrl)).Wait();
        //    return Regex.Unescape(City);
        //}
        #endregion
        #endregion
        #region 爬取二手车之家
        #region 获取品牌
        //https://www.che168.com/Handler/ScriptCarList_V1.ashx?needData=1

        public static string GetCheHomePinPai()
        {
            var PinPaiUrl = "https://www.che168.com/Handler/ScriptCarList_V1.ashx?needData=1";
          
            BaseCrawler baseCrawler = new BaseCrawler();
            ArrayList arrayid = new ArrayList();
            ArrayList arrayname = new ArrayList();
            ArrayList list = new ArrayList();
            baseCrawler.OnCompleted += (s, e) =>
            {
                string Pinpai = e.PageSource;
                // Console.WriteLine(Pinpai);
                int One = Pinpai.IndexOf('3');
                string Pstr = Pinpai.Substring(One, Pinpai.Length - One-2);
                string[] PPStr = Pstr.Split(',');              
                for (int i = 0; i <PPStr.Count(); i++)
                {
                   // Console.WriteLine(PPStr[i]);
                    arrayid.Add(PPStr[i]);
                    i++;
                   
                }              
                for (int i = 1; i < PPStr.Count(); i++)
                {
                   // Console.WriteLine(PPStr[i]);
                    arrayname.Add(PPStr[i]);
                    i++;
                }
                for (int i = 0; i < arrayid.Count; i++)
                {
                    Dictionary<object, object> dic = new Dictionary<object, object>();
                    dic.Add("PinPaiId",arrayid[i]);
                    dic.Add("PinPaiName", arrayname[i]);
                    list.Add(dic);
                }
               
              
               
            };
            baseCrawler.ErStart(new Uri(PinPaiUrl)).Wait();
            string Pjson = JsonConvert.SerializeObject(list);
            //  Console.WriteLine(Pjson);
            return Pjson;
        }
        #endregion
        #region 获取车系
        /// <summary>
        /// 获取二手车之家车系
        /// </summary>
        /// <param name="bid">汽车品牌ID</param>
        /// <returns></returns>
        public static string GetCheHomeSeries(string bid)
        {
            var Url = "https://www.che168.com/Handler/ScriptCarList_V1.ashx?seriesGroupType=2&needData=2&bid="+bid;
            ArrayList SeriesID = new ArrayList();
            ArrayList SeriesName = new ArrayList();
            Dictionary<object, object> SeriesDic = new Dictionary<object, object>();
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                string Data = e.PageSource;
                //  Console.WriteLine(SeriesData);
                int BeginIndex = Data.LastIndexOf("=")+2;
                int OverIndex = Data.Length - BeginIndex-2;
                string SeriesData = Data.Substring(BeginIndex, OverIndex);
                string[] SeriesInfo = SeriesData.Split(',');
                for (int i = 0; i < SeriesInfo.Length; i++)
                {
                     SeriesID.Add(SeriesInfo[i]);
                    //Console.WriteLine(SeriesInfo[i]);
                    i++;
                }
                for (int i = 1; i < SeriesInfo.Length; i++)
                {
                    SeriesName.Add(SeriesInfo[i]);
                    i++;
                }
                for (int i = 0; i < SeriesID.Count; i++)
                {
                    SeriesDic.Add(SeriesID[i], SeriesName[i]);
                }
            };
            baseCrawler.ErStart(new Uri(Url)).Wait();
            string SeriesJson = JsonConvert.SerializeObject(SeriesDic);
            return SeriesJson;
        }
        #endregion
        #region 获取车型
        public static string UsedCarInfo;
        public static string CarModel(string seriesidId)
        {
            var ModelUrl = "https://www.che168.com/Handler/ScriptCarList_V1.ashx?seriesGroupType=2&needData=3&seriesid="+seriesidId;
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                UsedCarInfo = e.PageSource;
                //Console.WriteLine(e.PageSource);
            };
            baseCrawler.ErStart(new Uri(ModelUrl)).Wait();
            return UsedCarInfo;
        }
        #endregion
        #region 获取车价
        public static string PriceStr;
        /// <summary>
        /// 获取车价
        /// </summary>
        /// <param name="pid">省份id</param>
        /// <param name="cid">城市id</param>
        /// <param name="mileage">行驶里程  单位： 公里</param>
        /// <param name="time">首次上牌时间 格式：xxxx-xx</param>
        /// <param name="specid">车型Id</param>
        /// <returns></returns>
        public static string GetPrice(string pid,string cid,string mileage,string time,string specid)
        {
           // https://pinguapi.che168.com/v1/auto/usedcarassess.ashx?_appid=pc.pingu&_sign=&encoding=gb2312&pid=330000&cid=330100&mileage=4000&firstregtime=2018-02&specid=32644&iscondition=1&_appversion=2.04v&mark=uahp10004
            var url = "https://pinguapi.che168.com/v1/auto/usedcarassess.ashx?_appid=pc.pingu&_sign=&encoding=gb2312&pid="+pid+"&cid="+cid+"&mileage="+mileage+"&firstregtime="+time+"&specid="+specid+"&iscondition=1&_appversion=2.04v&mark=uahp10004";
            BaseCrawler baseCrawler = new BaseCrawler();
            baseCrawler.OnCompleted += (s, e) =>
            {
                //  Console.WriteLine(e.PageSource);
                JObject Price = (JObject)JsonConvert.DeserializeObject(e.PageSource);
                //Console.WriteLine(Price);
                PriceStr= Price["result"].ToString();
               // Console.WriteLine(result);
               
            };
            baseCrawler.ErStart(new Uri(url)).Wait();
            return PriceStr;
        }
        #endregion
        #region 获取省市列表      
        public static string GetProvinces()
        {
            var url = "https://www.che168.com/pinggu/";
            BaseCrawler baseCrawler = new BaseCrawler();
            ArrayList list = new ArrayList();
            baseCrawler.OnCompleted += (s, e) =>
            {
                // Console.WriteLine(e.PageSource);
                HtmlDocument document = new HtmlDocument();
                document.LoadHtml(e.PageSource);
                HtmlNodeCollection collection = document.DocumentNode.SelectNodes("//div[@class='city']/a");
                if (collection != null)
                {
                   
                    foreach (var item in collection)
                    {
                        string PId = item.Attributes["pid"].Value;
                        // Console.WriteLine(PId);
                        string Pname = item.Attributes["pidName"].Value;
                        string Cid = item.Attributes["cid"].Value;
                        string Cname = item.InnerText;
                        //Console.WriteLine(Pname);
                        Dictionary<object, object> dictionary = new Dictionary<object, object>();
                        Dictionary<object, object> cdic = new Dictionary<object, object>();
                        dictionary.Add("PrvoinceId",PId);
                        dictionary.Add("ProvinceName", Pname);
                        cdic.Add("CityId", Cid);
                        cdic.Add("CityName", Cname);
                        dictionary.Add("data", cdic);
                        list.Add(dictionary);
                    }

                }
            };
            baseCrawler.ErStart(new Uri(url)).Wait();
            return JsonConvert.SerializeObject(list);
        }
        #endregion
        #endregion
    }
    #region 汽车品牌类
    /// <summary>
    /// 汽车品牌
    /// </summary>
    public class ChePinPai
    {
        public int PinPaiId { get; set; }
        public string PinPaiName { get; set;}
    }
    #endregion
    #region 汽车车系类
    /// <summary>
    /// 汽车车系
    /// </summary>
    public class CheSeries
    {
        public int series_id { get; set; }
        public string series_name { get; set; }
        /// <summary>
        /// 是否是新能源
        /// </summary>
        public string is_green { get; set; }
        /// <summary>
        /// 车系分组
        /// </summary>
        public string series_group_name { get; set; }
    }
    #endregion
    #region 汽车估价
    public class ChePrice
    {
        public ArrayList price { get; set; }
        //public string price1 { get; set; }
        //public string price2 { get; set; }
        //public string price3 { get; set; }
        //public string price4 { get; set; }
        //public string price5 { get; set; }
        //public string price6 { get; set; }
        //public string price7 { get; set; }

    }
    #endregion

}
